<script setup>
import * as echarts from "echarts";
import { ref, onMounted, watch } from "vue";

// 接收父组件传递的图表数据
const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
});

// 定义颜色映射
const colorMap = {
  租金收入: "#4caf50",
  费用支出: "#ff9800",
  企业欠费: "#f44336",
  总资产: "#2196f3",
  总负债: "#ff5722",
  净利润: "#8bc34a",
};

const chartRef = ref(null);

// 初始化图表
const initChart = () => {
  const chartInstance = echarts.init(chartRef.value);

  let option;

  if (props.chartData.chart_type === "pie") {
    // 如果是饼图，配置饼图的样式
    option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: ¥{c} ({d}%)", // 提示框显示格式
      },
      legend: {
        data: props.chartData.datasets.map((item) => item.name),
        bottom: 20,
      },
      series: props.chartData.datasets.map((item) => ({
        name: item.name,
        type: "pie",
        radius: "50%", // 饼图半径
        data: item.data.map((value, index) => ({
          value,
          name: props.chartData.labels[index],
        })),
        itemStyle: {
          color: colorMap[item.name] || "#000000",
        },
        label: {
          show: true, // 显示标签
          position: "outside", // 标签位置
          formatter: "{b}: ¥{c} ({d}%)", // 标签格式
        },
      })),
    };
  } else {
    // 否则配置折线图或者柱状图
    option = {
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: props.chartData.datasets.map((item) => item.name),
        bottom: 20,
      },
      xAxis: {
        type: "category",
        data: props.chartData.labels,
      },
      yAxis: {
        type: "value",
        name: "金额(¥)",
        axisLabel: {
          formatter: "¥{value}",
        },
      },
      series: props.chartData.datasets.map((item) => ({
        name: item.name,
        type: props.chartData.chart_type, // 使用折线图或柱状图
        data: item.data,
        smooth: true, // 平滑曲线
        itemStyle: {
          color: colorMap[item.name] || "#000000",
        },
      })),
    };
  }

  chartInstance.setOption(option);

  // 窗口大小调整时重新渲染图表
  window.addEventListener("resize", () => {
    chartInstance.resize();
  });
};

// 在组件挂载后初始化图表
onMounted(() => {
  initChart();
});

// 监听 chartData 的变化，重新渲染图表
watch(
  () => props.chartData.chart_type,
  () => {
    initChart(); // 重新初始化图表
  },
  { immediate: true }
);
</script>

<template>
  <div ref="chartRef" class="chart" />
</template>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 5px;
}
</style>
